/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 20, 2012  2:37:26 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.outbound
 * File Name : FiArreceiptreOutbService.java
 * TODO
 */
package sap.business.fi.outbound;

import java.util.ArrayList;
import java.util.List;

import jpa.entitys.synchro.staging.FiArinvoicereceOutb;
import jpa.entitys.synchro.staging.FiArreceiptreOutb;
import jpa.entitys.synchro.staging.SdChargecode;
import jpa.entitys.synchro.staging.SdCustoRequDeducOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.FiArinvoicereceOutbServices;
import jpa.service.synchro.staging.FiArreceiptreOutbServices;
import jpa.service.synchro.staging.SdCustoRequDeducOutbServices;

import org.apache.log4j.Logger;

import promis.utility.CommonService;

import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;

/**
 * @author chatree
 *
 */
public class FiArreceiptreOutbService extends SynchroOutAbstract {
	
	
	private static final Logger log = Logger.getLogger(FiArreceiptreOutbService.class);
	private FiArreceiptreOutbServices fiArreceiptreOutbServ;


	/**
	 * 
	 */
	public FiArreceiptreOutbService() {
		// TODO Auto-generated constructor stub
		try {
			
			this.sap_bapi = "ZIN_FIAR_RECEIPT_RE";
			this.sap_table = "ACCT_DATA";
			this.sap_table_return = "RETURN";
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {
				FiArreceiptreOutb model = (FiArreceiptreOutb)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				jcoTable.setValue("INTERFACE_NO", "FI-T1-050");
				jcoTable.setValue("BUKRS", model.getSapCompanyCode());
				jcoTable.setValue("BLDAT", model.getReceiptDate());	
				jcoTable.setValue("BUDAT", model.getReceiptDate());	
				jcoTable.setValue("WAERS", model.getCurrency());
				jcoTable.setValue("KURSF", model.getExchangeRate());				
				jcoTable.setValue("CONTRACT_NO", model.getRefContractNo());	
				jcoTable.setValue("PROMIS_UNIT_CODE", model.getUnitNumber());
				
				if(!CommonService.IsNull(model.getPaymentType()))
				{
					jcoTable.setValue("SGTXT", model.getPaymentTypeDesc());
					jcoTable.setValue("BKTXT", model.getPaymentTypeDesc());
					jcoTable.setValue("CHARGE_CODE", model.getPaymentType());
					
					//2012-09-25*************************************************************
					//jcoTable.setValue("EXCWHT", model.getAmountReceived());
					jcoTable.setValue("EXCWHT", model.getNetAmountReceined());
					
					jcoTable.setValue("ITEM_NO", model.getInstallmentNumber());
				}
				else
				{
					jcoTable.setValue("SGTXT", "");
					jcoTable.setValue("BKTXT", "");
					jcoTable.setValue("CHARGE_CODE", "");
					
					//2012-09-25*************************************************************
					//jcoTable.setValue("EXCWHT", model.getAmountReceived());
					jcoTable.setValue("EXCWHT", model.getNetAmountReceined());
					
					jcoTable.setValue("ITEM_NO", model.getChargeCode());
				}
				
				jcoTable.setValue("PMT_FLAG", model.getFullPartialFlag());				
				jcoTable.setValue("SPESW", model.getBankCharge());
				jcoTable.setValue("VALUT", model.getReceiptDate());	
				jcoTable.setValue("ZLSCH", model.getReceivedType());
				jcoTable.setValue("ZUONR", model.getReceiptDocNo());					
				jcoTable.setValue("PLANT_CODE", model.getSapPlantCode());
				jcoTable.setValue("XREF2", model.getRefDocument());
				jcoTable.setValue("HKONT", model.getCustomerCode());
				jcoTable.setValue("DUEON", model.getChequeDueDate());
				jcoTable.setValue("WDATE", model.getChequeDueDate());	
				jcoTable.setValue("WNAME", "");
				jcoTable.setValue("WORT1", "");
				jcoTable.setValue("BOENO", model.getChequeNumber());
				jcoTable.setValue("BANK", model.getChequeIssuingBank());
				
				jcoTable.setValue("CARD_NO", model.getCardNo());				
				jcoTable.setValue("BANK_KEY", model.getBankCardReader());
				jcoTable.setValue("PAY_CARD_TYP", model.getCreditCardType());
								
				jcoTable.setValue("WBZOG", model.getCustomerName());
				//jcoTable.setValue("WORT2", model.getAddressCode()); //Eaun don't Send.
				jcoTable.setValue("ACCOU", model.getChequePayeeAcNumber());
				
				jcoTable.setValue("FROM_PLANT", model.getFromSapPlantCode());
				jcoTable.setValue("FROM_UNIT", model.getFromUnitNumber());
				jcoTable.setValue("FROM_BUILDING", model.getFromBuildingPhaseCode());
				jcoTable.setValue("FROM_FLOOR", model.getFromFLoorZoneCode());				
				jcoTable.setValue("STATUS", model.getStatus());
				
	        }
		}
		
		super.SynchroToSap(jcoFunction, jcoTable, value_list);
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		List<FiArreceiptreOutb> lst = new ArrayList<FiArreceiptreOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				FiArreceiptreOutb model = fiArreceiptreOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				//log.info("PROMIS_TXN_ID = " + jcoTable_return.getString("PROMIS_TXN_ID") + " // MSG_CODE : " + CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			fiArreceiptreOutbServ.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<FiArreceiptreOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<FiArreceiptreOutb> newlst = new ArrayList<FiArreceiptreOutb>();
				for(FiArreceiptreOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				 new FiArreceiptreOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	/**
	 * 
	 * @param company 'SP'
	 * @param project 'SPLCITY-SRI'
	 * @param refDocumentNo as 'Sales Booking Number' or 'Sales Contract No' 
	 * @param status  'A','Z'
	 * @param issync 'Y','N'
	 * @throws Exception
	 */
	public void SendingToSAP(String company, String project, String refDocumentNo, String status, String instanceNo, String issync) throws Exception {
		log.info("Start SendingToSAP.");		
		try{
			
			fiArreceiptreOutbServ = new FiArreceiptreOutbServices(this.emSynchro);			
			
			//Group By Receipted Document Number 
			List<String> rr_doc_no_lst = fiArreceiptreOutbServ.GroupByDocumentNo(company, project, refDocumentNo, status, issync);
			if(rr_doc_no_lst != null)
			{				
				for(String receiptDocNo : rr_doc_no_lst)
				{
					log.info(" receiptDocNo = " + rr_doc_no_lst);
					List<FiArreceiptreOutb> value_list = null;
					try{
						
						List<FiArreceiptreOutb> lst =  fiArreceiptreOutbServ.findByDocumentNo(company, project, receiptDocNo, status, issync);
						if(!CommonService.IsNull(lst))
						{
							//this.sap_structure = "ACCT_DATA";
							this.jco_conn  = new Connection();						

							//Get SAP BAPI function 
							JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
							
							//Get SAP Staging table
							JCoTable jcoTable = jco_conn.getTables(sap_table);
							
							value_list = lst; // fiArreceiptreOutbServ.findIsSync("N");
							
							//SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
							SynchroToSap(jcoFunction, jcoTable, value_list);
							
							//Get SAP Staging table retrun message
							JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
							CallbackMessageFromSap(jcoTable_return);
							
						}else
							log.warn(" findByRefDocumentNo  Receipt is null  company = "+ company +" , project = "+ project +" :: refDocumentNo = " + refDocumentNo + " , status = "+ status);
						
					}catch(Exception e){
						UpdateStagingWhenError(value_list, e);
						log.error(e);
						throw e;
					}									
				}
			}else 
				log.warn(" Can't Group By Receipted Document Number !!! ");
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	
	public void SendingToSAP(List<FiArreceiptreOutb> value_list) throws Exception {
		log.info("Start SendingToSAP.");
		try{
			
			if(!CommonService.IsNull(value_list)){
				//this.sap_structure = "ACCT_DATA";
				this.jco_conn  = new Connection();

				//Get SAP BAPI function 
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				fiArreceiptreOutbServ = new FiArreceiptreOutbServices(this.emSynchro);
				
				//SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
				
			}else
				log.info("else ---. ");
			
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);
			
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	@Deprecated
	private void Start() throws Exception
	{
		
		//this.sap_structure = "ACCT_DATA";
		this.jco_conn  = new Connection();
		jco_conn.CreatedJCOConnectionProperty();

		//Get SAP BAPI function 
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		fiArreceiptreOutbServ = new FiArreceiptreOutbServices(this.emSynchro);
		List<FiArreceiptreOutb> value_list = fiArreceiptreOutbServ.findIsSync("N");
		
		//SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
				
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try{
			
			FiArreceiptreOutbService obj = new FiArreceiptreOutbService();
			obj.Start();
			
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			System.err.println(ex.getMessage());
		}

	}

}
